<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="关键字" size="small"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getTableData" icon="el-icon-search" size="small">执行查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">讲师新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="头像">
        <template scope="scope">
          <el-image style="width: 40px;height: 40px"
                    :src="scope.row.headImg"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称">
      </el-table-column>
      <el-table-column prop="position" label="职位">
      </el-table-column>
      <el-table-column prop="tags" label="标签">
      </el-table-column>
      <el-table-column prop="intro" label="介绍" width="200">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <div style="width: 400px;">{{ scope.row.intro }}</div>
            <div slot="reference" class="name-wrapper">
              <el-tag>
                {{ scope.row.intro }}
              </el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template scope="scope">
          <el-button size="small" @click="handleModify(scope.$index, scope.row)" icon="el-icon-edit" type="primary">编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" icon="el-icon-remove">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" icon="el-icon-remove" size="small">
        批量删除
      </el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :total="total" style="float:right;">
      </el-pagination>
    </el-col>
    <!--新增界面-->
    <el-dialog title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" ref="addForm">
        <el-form-item label="分类标题" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="addForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="技术栈" prop="technology">
          <el-input v-model="addForm.technology" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="addForm.position" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="headImg" label="头像">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastdfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
<!--        <el-form-item prop="logo" style="width: 400px">-->
<!--          &lt;!&ndash;<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>&ndash;&gt;-->
<!--          <el-upload-->
<!--              class="upload-demo"-->
<!--              action="http://java219.oss-cn-chengdu.aliyuncs.com"-->
<!--              :data="uploadPicData"-->
<!--              :before-upload="beforePicUpload"-->
<!--              :on-success="handlePicSuccess"-->
<!--              :limit="1">-->
<!--            <el-button size="small" type="primary" icon="el-icon-picture-outline">上传封面</el-button>-->
<!--            &nbsp;&nbsp;<span slot="tip" class="el-upload__tip">支持500kb，格式jpg</span>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
        <!--        <el-form-item label="头像" prop="headImg">-->
        <!--          <el-input v-model="addForm.headImg" auto-complete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="标签" prop="tags">
          <el-input v-model="addForm.tags" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addTeacher">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 5,
      addFormVisible: false,
      listLoading: false,
      title: "",
      fileList: [],
      sels: [],
      addForm: {
        name: "",
        intro: "",
        technology: "",
        position: "",
        headImg: "",
        tags: ""
      }
    }

  },
  methods: {
    selsChange(sels) {
      this.sels = sels;
    },
    handleAdd() {
      this.addForm = {
        id: null,
        name: "",
        intro: "",
        technology: "",
        position: "",
        headImg: "",
        tags: ""
      };
      this.title = "新 增";
      this.fileList = [];
      this.addFormVisible = true;
    },
    handleModify(index, row) {
      //克隆：防止对象引用修改显示的数据
      this.addForm = Object.assign({}, row);
      //this.getManagers();
      this.title = " 修 改 "
      this.fileList = [];
      if(this.addForm.headImg){//有值
        let arr = this.addForm.headImg.split(",");
        for (var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
        }
      }
      //显示对话框
      this.addFormVisible = true;
    },
    //性别显示转换
    formatState: function (row, column) {
      return row.sex == 1 ? '禁用' : '启用';
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getTableData();
    },
    //获取用户列表
    getTableData() {
      let para = {
        page: this.page,
        keyword: this.filters.keyword
      };
      this.listLoading = true; //显示加载圈
      this.$http.post("/course/teacher/pageList", para).then(result => {
        this.total = result.data.data.total;
        this.tableData = result.data.data.rows;
        this.listLoading = false;  //关闭加载圈
      });
    },
    // 删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => { //点击确认之后要执行的代码
        //获取id
        var id = row.id;
        //显示加载框
        this.listLoading = true;
        this.$http.delete("/course/teacher/" + id).then(res => {
          if (res.data.success) {//删除成功
            this.$message.success('删除成功'); //3s自动消失
            var totalPage = Math.ceil(this.total / this.pageSize);
            if (totalPage == this.page && this.page > 1 && (this.totals - 1) % this.pageSize == 0) {
              this.page = this.page - 1;
            }
            this.getTableData();
          } else {
            this.$message.error('系统繁忙，请稍后重试【500】');
          }
          this.listLoading = false;//关闭加载框
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试【400,404】');
        })
      }).catch(() => { //点击取消之后要执行的代码
      });
    },
    // 批量删除
    batchRemove: function () {
      //获取被选中对象的id们
      var ids = this.sels.map(item => item.id); //[1,2,3]
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/course/teacher", ids).then(res => {
          if (res.data.success) {//删除成功
            this.$message.success('删除成功'); //3s自动消失
            this.page = 1;
            this.getTableData();
          } else {
            this.$message.error('系统繁忙，请稍后重试【500】');
          }
          this.listLoading = false;//关闭加载框
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试【400,404】');
        })
      }).catch(() => {
      });
    },
    // 新增
    addTeacher() {
      //提交
      this.$http.post("/course/teacher/save", this.addForm).then(res => {
        //{success: true, ..
        var ajaxResult = res.data;
        if (ajaxResult.success) {
          this.addFormVisible = false;
          this.$notify({
            message: '提交成功',
            type: 'success'
          });
          this.getTableData();
        } else {
          this.$notify({
            message: ajaxResult.message,
            type: 'error'
          });
        }
      });
    },

    handleSuccess(response, file, fileList) {
      //处理resources - 数据库操作
      if (this.addForm.headImg) { //有值  /group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk505.png
        this.addForm.headImg = this.addForm.headImg + "," + response.resultObj;
      } else {
        this.addForm.headImg = response.resultObj;
      }

      //处理fileList - 页面回显的
      this.fileList = [];//清空
      if (this.addForm.headImg) {
        var resourcesArr = this.addForm.headImg.split(",");
        for (var i = 0; i < resourcesArr.length; i++) {
          this.fileList.push({url: "http://123.207.27.208" + resourcesArr[i]})
        }
      }
    },

    handleRemove(file, fileList) {
      //{url: "http://123.207.27.208/group1/M00/00/02/CgAIC2KevEeAX2T4AAEUusLjqqk161.png"}
      //console.log(file);
      //1.调用删除接口删除 fastdfs上的图片
      let url = file.url
      let path = url.substring(url.indexOf("/group1"));
      this.$http.delete("/fastdfs?path=" + path).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败");
        }
      })

      //2.对resource做处理 ：加入path="/group1/MxVcQ8663.jpg"
      // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg,/group1/MxVcQ8663.jpg
      if (this.addForm.headImg) {//只有值
        //["/group1/M00cQ8663.jpg","/group1/MxVcQ8663.jpg","/group1/MxVcQ8663.jpg"]
        let arr = this.addForm.headImg.split(",");
        for (var i = 0; i < arr.length; i++) {
          if (arr[i] == path) {
            //从i开始删除，向后删除1个
            arr.splice(i, 1);
            break;
          }
        }
        this.addForm.headImg = arr.join(","); // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg
      }

      //3.对fileList做处理
      this.fileList = [];
      if (this.addForm.headImg) {//有值
        let arr = this.addForm.headImg.split(",");
        for (var i = 0; i < arr.length; i++) {
          this.fileList.push({"url": "http://123.207.27.208" + arr[i]});
        }
      }
    }
  },

  mounted() {
    this.getTableData();
  }
}

</script>

<style scoped>

</style>